<template>
  <Page ref="page" title="练习记录">
    <template #navBarCustom>
      <NewBar
        title="练习记录"
        :tabs="subjects.list"
        :usedSubject="subjects.usedSubject"
        :moreSubject="subjects.moreSubject"
        :active="subjects.active"
        @change="subjects.onChange($event)"
      >
      </NewBar>
    </template>
    <template #content>
      <div class="w-full h-full bg-F4F7FB flex flex-col">
        <div class="main flex-1 flex flex-col bg-white">
          <!-- 练习统计 -->
          <div class="statistics flex justify-between">
            <div class="item flex flex-col justify-center items-center bg-51C3FF-10">
              <div class="text-51C3FF" style="font-size: 0.44rem">
                {{ records.total }}
              </div>
              <div class="text-333" style="font-size: 0.24rem">练习次数</div>
            </div>
            <div class="item flex flex-col justify-center items-center bg-51C3FF-10">
              <div class="text-51C3FF" style="font-size: 0.44rem">
                {{ records.totalTime | totalHours
                }}<span class="text-333" style="font-size: 0.2rem">时</span
                >{{ records.totalTime | totalMinutes
                }}<span class="text-333" style="font-size: 0.2rem">分</span>
              </div>
              <div class="text-333" style="font-size: 0.24rem">练习时长</div>
            </div>
          </div>
          <!-- 练习列表 -->
          <scroll-view
            ref="scroll"
            @scrolltolower="records.getList()"
            class="list flex-1 overflow-scroll w-full bg-white px-20px box-border"
          >
            <div
              v-for="i in records.list"
              :key="i.id"
              class="item w-full flex px-20px mb-20px box-border"
              @click="goToRecordDetail(i.id)"
            >
              <div class="main flex-1 h-full flex flex-col justify-center">
                <div class="name text-333 font-medium">
                  {{ i.practiceName }}
                </div>
                <div class="detail flex text-A3A3A3 mt-4px items-center">
                  <div class="">{{ $utils.formatTimeStamp(i.endTime) }}</div>
                  <div class="divide">|</div>
                  <div class="">共{{ i.questionNum }}题</div>
                  <div class="divide">|</div>
                  <div class="">
                    {{ i.difficultyLevel | difficultyLevelName(questionDifficultyType) }}
                  </div>
                  <div class="divide">|</div>
                    <el-rate v-model="i.difficultyLevelNumber" disabled />
                  <div class="divide">|</div>
                  <div class="">用时:{{ i.time }}</div>
                </div>
              </div>
              <StatisticsXkw :correctRate="parseFloat(i.correctRate)" v-if="!isEnglishSubject" />
              <StatisticsEnglish
                :score="parseFloat(i.score)"
                :scoreaverage="parseInt(parseFloat(i.score)*100/parseFloat(i.allScore))"
                v-else
              />
            </div>

            <LoadMore
              cssStyle="padding-top:0.1rem"
              :loading="records.loading"
              :has-more="records.hasMore"
              @click="records.getList()"
            />
          </scroll-view>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page/newPage'
import NewBar from '@/components/subject/tabs/newTabs'
import SubjectTabs from '@/components/subject/tabs'
import ScrollView from '@/components/scroll-view'
import LoadMore from '@/components/load-more'
import StatisticsXkw from './components/statistics-xkw'
import StatisticsEnglish from './components/statistics-english'
import { getStudentCoursesList, getKpointPracticeRecord } from '@/api/exercise/record'
import { debounce } from '@/utils'
import { mapActions } from 'vuex'

export default {
  components: {
    Page,
    SubjectTabs,
    ScrollView,
    LoadMore,
    StatisticsXkw,
    StatisticsEnglish,
    NewBar
  },
  filters: {
    difficultyLevelName: (level, types) => {
      const { label = '' } = types.find((type) => type.value == level)
      return label
    },
    totalHours: (value) => {
      const h_pattern = new RegExp(/[0-9]+时/)

      const res = h_pattern.exec(value)

      if (res) {
        return res[0].replace('时', '')
      }

      return 0
    },
    totalMinutes: (value) => {
      const m_pattern = new RegExp(/[0-9]+分/)

      const res = m_pattern.exec(value)

      if (res) {
        return res[0].replace('分', '')
      }

      return 0
    }
  },
  data() {
    return {
      questionDifficultyType: [],
      // 学科栏目
      subjects: {
        vm: this._self,
        active: '',
        list: [],
        usedSubject: [],
        moreSubject: [],
        getList: async function (subjectId, callback) {
          const { data = [] } = await getStudentCoursesList()
          const subjects = await this.vm.getDictByType('subject')
          this.usedSubject = subjects.filter((item) => {
            return ['1', '2', '3', '4', '5'].includes(item.value)
          })
          this.moreSubject = subjects.filter((item) => {
            return !['1', '2', '3', '4', '5'].includes(item.value)
          })
          // 如果没有开通的科目，弹出弹窗
          if (data.length === 0) {
            this.vm.$popup.show({
              type: 'alert',
              success: (popup) => {
                popup.$on('confirm', () => {
                  this.vm.$popup.hide('alert')
                  this.vm.$router.back()
                })
                popup.setData({
                  content: '没有已开通的科目'
                })
              }
            })
            return
          }

          this.active = subjectId ? subjectId : data[0].value
          this.list = data
          callback('')
        },
        onChange: debounce(function (subjectId) {
          // 上传模块使用时间
          this.vm.$store.state.moduleUse.currentModuleUse.submit()
          // 重置
          this.vm.$store.state.moduleUse.currentModuleUse.onSubjectChange(subjectId)

          this.active = subjectId
          history.replaceState(
            {},
            '',
            location.hash.replace(/subjectId=[\W\w]+/, `subjectId=${subjectId}`)
          )
          this.vm.records.reset()
          this.vm.records.getList()
        }, 300)
      },
      // 练习记录列表
      records: {
        vm: this._self,
        pageNo: 1,
        pageSize: 10,
        loading: false,
        hasMore: true,
        total: 0,
        totalTime: '',
        list: [],
        getList: debounce(async function () {
          if (this.loading) return

          const lastScrollTop = this.vm.$refs.scroll.getScrollTop()

          this.loading = true

          const {
            data: { list, total, totalTime }
          } = await getKpointPracticeRecord({
            pageNo: this.pageNo,
            pageSize: this.pageSize,
            subjectId: this.vm.subjects.active
          })

          if (list.length < this.pageSize) {
            this.hasMore = false
          }

          if (list.length > 0) {
            this.list = this.list.concat(
              list.map((item) => {
                const { questionNumSuccess = 0, questionNum = 0 } = item

                if (!questionNumSuccess || !questionNum) {
                  item['correctRate'] = 0
                } else {
                  item['correctRate'] = (
                    (parseInt(questionNumSuccess) / parseInt(questionNum)) *
                    100
                  ).toFixed(1)
                }
                item.difficultyLevelNumber=this.vm.difficultyLevelNumber(item.difficultyLevel,this.vm.questionDifficultyType)
                console.log(item)
                return item
              })
            )

            this.pageNo++
            this.vm.$nextTick(() => {
              this.vm.$refs.scroll.setScrollTop(lastScrollTop)
            })
          }

          this.total = total
          this.totalTime = totalTime
          this.loading = false
        }, 300),
        reset: function () {
          this.pageNo = 1
          this.pageSize = 20
          this.loading = false
          this.hasMore = true
          this.list = []
        }
      }
    }
  },
  computed: {
    isEnglishSubject() {
      if (this.subjects.active === '66') {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    difficultyLevelNumber(level, types){
      const { label = '' } = types.find((type) => type.value == level)
      let number = 0
      switch (label) {
        case '容易':
          number = 1
          break
        case '较易':
          number = 2
          break
        case '适中':
          number = 3
          break
        case '较难':
          number = 4
          break
        case '困难':
          number = 5
          break
        default:
          number = 0
          break
      }
      return number
    },
    ...mapActions(['getDictByType']),
    async init() {
      const { subjectId = '' } = this.$route.query
      this.questionDifficultyType = await this.getDictByType('question_difficulty_type')
      this.subjects.getList(subjectId, () => {
        this.records.getList()
      })
    },
    goToRecordDetail(id) {
      this.$router.push(
        `/pages/exercise/record/detail/${
          !this.isEnglishSubject ? 'xkw' : 'english'
        }/index?id=${id}&subjectId=${this.subjects.active}`
      )
    }
  }
}
</script>

<style lang="scss">
.main {
  overflow: hidden;

  .statistics {
    padding: 30px 326px;

    .item {
      width: 206px;
      height: 102px;
      border-radius: 5px;
    }
  }

  .list {
    .item {
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #e8e8e8;
      border-radius: 10px;

      .main {
        .name {
          font-size: 28px;
        }

        .detail {
          font-size: 24px;

          .divide {
            padding: 0 16px;
          }
        }
      }
    }
  }
}
</style>
